package com.airbat.prize.modules.system.controller.dept;

import com.airbat.prize.common.enums.CommonStatusEnum;
import com.airbat.prize.common.pojo.CommonResult;
import com.airbat.prize.modules.system.controller.dept.vo.dept.*;
import com.airbat.prize.modules.system.convert.dept.SysDeptConvert;
import com.airbat.prize.modules.system.dal.dataobject.dept.SysDeptDO;
import com.airbat.prize.modules.system.service.dept.SysDeptService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

import static com.airbat.prize.common.pojo.CommonResult.success;

@Api(tags = "部门")
@RestController
@RequestMapping("/system/dept")
@Validated
public class SysDeptController {

    @Resource
    private SysDeptService deptService;

    @PostMapping("create")
    @ApiOperation("创建部门")
    @PreAuthorize("@ss.hasPermission('system:dept:create')")
    public CommonResult<Long> createDept(@Valid @RequestBody SysDeptCreateReqVO reqVO) {
        if (reqVO.getParentId() == null)
            reqVO.setParentId(0L);
        Long deptId = deptService.createDept(reqVO);
        return success(deptId);
    }

    @PutMapping("update")
    @ApiOperation("更新部门")
    @PreAuthorize("@ss.hasPermission('system:dept:update')")
    public CommonResult<Boolean> updateDept(@Valid @RequestBody SysDeptUpdateReqVO reqVO) {
        if (reqVO.getParentId() == null)
            reqVO.setParentId(0L);
        deptService.updateDept(reqVO);
        return success(true);
    }

    @DeleteMapping("delete")
    @ApiOperation("删除部门")
    @ApiImplicitParam(name = "id", value = "编号", required = true, example = "1024", dataTypeClass = Long.class)
    @PreAuthorize("@ss.hasPermission('system:dept:delete')")
    public CommonResult<Boolean> deleteDept(@RequestParam("id") Long id) {
        deptService.deleteDept(id);
        return success(true);
    }

    @GetMapping("/list")
    @ApiOperation("获取部门列表")
    @PreAuthorize("@ss.hasPermission('system:dept:query')")
    public CommonResult<List<SysDeptRespVO>> listDepts(SysDeptListReqVO reqVO) {
        List<SysDeptDO> list = deptService.getSimpleDepts(reqVO);
        list.sort(Comparator.comparing(SysDeptDO::getSort));
        return success(SysDeptConvert.INSTANCE.convertList(list));
    }

    @GetMapping("/list-type")
    @ApiOperation("获取部门列表")
    @PreAuthorize("@ss.hasPermission('system:dept:query')")
    public CommonResult<List<SysDeptRespVO>> listTypeDepts() {
        SysDeptListReqVO reqVO = new SysDeptListReqVO();
        reqVO.setStatus(CommonStatusEnum.ENABLE.getStatus());
        List<SysDeptDO> listAll = new ArrayList<>();
        List<SysDeptDO> list = deptService.getSimpleDepts(reqVO);
        {
            SysDeptDO gaDeptDO = new SysDeptDO();
            gaDeptDO.setId(10000L);
            gaDeptDO.setParentId(0L);
            gaDeptDO.setDeptType(0);
            gaDeptDO.setAreaType(3);
            gaDeptDO.setName("公安机关");
            listAll.add(gaDeptDO);
        }
        {
            SysDeptDO gaDeptDO = new SysDeptDO();
            gaDeptDO.setId(20000L);
            gaDeptDO.setParentId(0L);
            gaDeptDO.setDeptType(9);
            gaDeptDO.setAreaType(3);
            gaDeptDO.setName("行业监管部门");
            listAll.add(gaDeptDO);
        }
        List<SysDeptDO> listZw = list.stream().filter(tr -> tr.getDeptType() != null && tr.getDeptType().intValue() == 9).collect(Collectors.toList());
        listAll.addAll(listZw);
        for (SysDeptDO deptDO : listZw) {
            if (deptDO.getParentId() == null || deptDO.getParentId() <= 0)
                deptDO.setParentId(20000L);
        }
        List<SysDeptDO> listGa = list.stream().filter(tr -> tr.getDeptType() != null && tr.getDeptType().intValue() < 9).collect(Collectors.toList());
        listAll.addAll(listGa);
        for (SysDeptDO deptDO : listGa) {
            if (deptDO.getParentId() == null || deptDO.getParentId() <= 0)
                deptDO.setParentId(10000L);
        }
//        listAll.sort(Comparator.comparing(SysDeptDO::getSort));
        List<SysDeptRespVO> deptRespVOS = SysDeptConvert.INSTANCE.convertList(listAll);
        for (SysDeptRespVO deptRespVO : deptRespVOS) {
            if (deptRespVO.getId() == 10000L || deptRespVO.getId() == 20000L)
                deptRespVO.setIsDisabled(true);
        }
        return success(deptRespVOS);
    }

    @GetMapping("/list-all-simple")
    @ApiOperation(value = "获取部门精简信息列表", notes = "只包含被开启的部门，主要用于前端的下拉选项")
    @ApiImplicitParam(name = "deptType", value = "部门类型 0其他 1辖区派出所 2打黑办 9政务网", required = false, dataTypeClass = Long.class)
    public CommonResult<List<SysDeptSimpleRespVO>> getSimpleDepts(@RequestParam(value = "deptType", required = false) Integer deptType) {
        // 获得部门列表，只要开启状态的
        SysDeptListReqVO reqVO = new SysDeptListReqVO();
        reqVO.setStatus(CommonStatusEnum.ENABLE.getStatus());

        Map<Long, SysDeptDO> map = new HashMap<>();
        List<SysDeptDO> list = new ArrayList<>();
        List<SysDeptDO> listAll = deptService.getSimpleDepts(reqVO);
        if (deptType != null) {
            List<SysDeptDO> listTemp = listAll.stream().filter(tr -> tr.getDeptType().intValue() == deptType.intValue()).collect(Collectors.toList());
            for (SysDeptDO deptDO : listTemp) {
                map.put(deptDO.getId(), deptDO);

                Long parentId = deptDO.getParentId();
                while (true) {
                    if (parentId == null)
                        break;
                    SysDeptDO deptParent = deptService.getDeptFromCache(parentId);
                    if (deptParent == null)
                        break;

                    if (!map.containsKey(deptParent.getId()))
                        map.put(deptParent.getId(), deptParent);
                    parentId = deptParent.getParentId();

                }
            }
            list = new ArrayList<>(map.values());
        } else {
            list = listAll;
        }
        list.sort(Comparator.comparing(SysDeptDO::getSort));
        return success(SysDeptConvert.INSTANCE.convertList02(list));
    }

    @GetMapping("/get")
    @ApiOperation("获得部门信息")
    @ApiImplicitParam(name = "id", value = "编号", required = true, example = "1024", dataTypeClass = Long.class)
    @PreAuthorize("@ss.hasPermission('system:dept:query')")
    public CommonResult<SysDeptRespVO> getDept(@RequestParam("id") Long id) {
        return success(SysDeptConvert.INSTANCE.convert(deptService.getDept(id)));
    }

}
